import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mac
 * Date: 2022-08-31
 * Time: 16:06
 */
public class MyArrayList {
    public int[] array;
    public int arraySize;

    public MyArrayList(){
        this.array = new int[2];
    }

    //打印顺序表
    public void display(){
        for (int i = 0; i < this.arraySize; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    //获取顺序表有效数据长度
    public int size(){
        return this.arraySize;
    }

    //在pos位置新增元素
    public void addPos(int pos, int data){
        if (pos < 0 || pos > this.arraySize){
            System.out.println("位置不合法！");
            return;
        }
        //判满
        if (isFull()){
            this.array = Arrays.copyOf(this.array, this.array.length * 2);
            System.out.println("空间不足，已扩容成功");
        }
        for (int i = this.arraySize - 1; i >= pos; i--) {
            this.array[i + 1] = this.array[i];
        }
        this.array[pos] = data;
        this.arraySize++;
    }

    //判满
    public boolean isFull(){
        return this.array.length == this.arraySize;
    }

    //判断是否包含某个元素
    public boolean judgeData(int data){
        for (int i = 0; i < this.arraySize; i++) {
            if (this.array[i] == data){
                return true;
            }
        }
        return false;
    }

    //查找某个元素对应的位置
    public int findData(int data){
        for (int i = 0; i < this.arraySize; i++) {
            if (this.array[i] == data){
                return i;
            }
        }
        return -1;
    }

    //获取pos位置的值
    public int getPos(int pos){
        if (pos < 0 || pos >= this.arraySize){
            System.out.println("pos位置不合法！");
            return -1;
        }
        if (isEmpty()){
            System.out.println("顺序表为空！");
            return -1;
        }
        return this.array[pos];
    }

    //判空
    public boolean isEmpty(){
        return this.arraySize == 0;
    }

    //给pos位置的元素设置为value
    public void setPos(int pos, int value){
        if (pos < 0 || pos >= this.arraySize){
            System.out.println("pos位置不合法");
            return;
        }
        if (isEmpty()){
            System.out.println("顺序表为空！");
            return;
        }
        this.array[pos] = value;
    }

    //删除第一次出现的关键字
    public void remove(int key){
        if (isEmpty()){
            System.out.println("顺序表为空！");
            return;
        }
        int pos = findData(key);
        if (pos == -1){
            System.out.println("关键字不存在！");
            return;
        }
        for (int i = pos; i < this.arraySize - 1; i++) {
            this.array[i] = this.array[i + 1];
        }
        this.arraySize--;
    }

    //清空顺序表
    public void clear(){
        this.arraySize = 0;
        /*for (int i = 0; i < this.arraySize; i++) {
            this.array[i] = null;
        }*/
    }
}
